package com.zhugang.week02;

/**
 * @program algorithms
 * @description: removeElements
 * @author: chanzhugang
 * @create: 2022/05/29 14:59
 */
public class RemoveElements2 {

    /**
     * 203.移除链表元素
     *
     * @param head
     * @param val
     * @return
     */
    public ListNode removeElements(ListNode head, int val) {
        // 开辟新链表，遍历原链表，把节点值不等于val的节点追加到新链表尾部(尾插法)：tail.next = p; tail = p;
        ListNode headNode = new ListNode();
        ListNode tail = headNode;
        ListNode p = head;
        while (p != null) {
            // p.next节点记录下来
            ListNode temp = p.next;
            if (p.val != val) {
                // 此时p是尾节点
                p.next = null;
                tail.next = p;
                tail = p;
            }
            p = temp;
        }
        return headNode.next;
    }


    public ListNode removeElements2(ListNode head, int val) {
        // 找到前驱节点(prev.next.val == val)，删除节点, prev.next = prev.next.next; 处理head特殊情况
        if (head == null) {
            return null;
        }
        ListNode prev = head;
        while (prev.next != null) {
            if (prev.next.val == val) {
                // 找到前驱节点
                prev.next = prev.next.next;
            } else {
                // 往后挪一位
                prev = prev.next;
            }
        }
        if (head.val == val) {
            // 特殊处理头节点（头节点也满足）
            head = head.next;
        }

        return head;
    }

    public ListNode removeElements3(ListNode head, int val) {
        // 引入虚拟头节点，不用特殊处理头节点，virtual.next = head; prev = virtual
        ListNode virtualNode = new ListNode();
        virtualNode.next = head;
        ListNode prev = virtualNode;
        while (prev.next != null) {
            if (prev.next.val == val) {
                prev.next = prev.next.next;
            } else {
                prev = prev.next;
            }
        }
        return virtualNode.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}